package 栈;

import java.util.Arrays;

public class MyStack<T> {
    private T[] elem;
    private int top;

    public MyStack() {
        this.elem =(T[]) new Object[10];
    }
    //入栈
    public void push(T item) {
        //判断当前栈是否满了
        if (isFull()){
            //栈满则2倍扩容
            this.elem= Arrays.copyOf(this.elem,this.elem.length*2);
        }
        this.elem[top]=item;
        top++;
    }

    public boolean isFull() {
        return this.elem.length == this.top;
    }

    //出栈
    public T pop() {
        if (isEmpty()) {
            //栈为空，则抛出异常
            throw new UnsupportedOperationException("栈为空!");
        }
        return this.elem[--top];
    }
    //检查栈是否为空
    public boolean isEmpty() {
        return this.top==0;
        //return this.elem.length==0;
    }
    //弹出栈顶元素
    public T peek() {
        if (isEmpty()) {
            //栈为空，则抛出异常
            throw new UnsupportedOperationException("栈为空!");
        }
        return this.elem[this.top-1];
    }

}
